import { Injectable } from '@angular/core';
import { HttpService } from '../../shared/service/http.service';
@Injectable({
    providedIn: 'root',
})
// tslint:disable
export class IndexedDBService {
    private isdbSupported;
    private db;
    private defaultStore = "chat";
    private userInfo = "user";
    private unreadchat = "unreadchat";
    private unreadNum = "unreadNum";
    // private readyToSend = "readyToSend";
    private dbName = "xw_im";

    public request;

    constructor(private http: HttpService) {
        this.onPageLoad();
    }
    onPageLoad() {
        try {
            const indexedDB = window.indexedDB;
            if (indexedDB) {
                this.isdbSupported = indexedDB;
            }
            const openReq = indexedDB.open(this.dbName, 1);
            openReq.onupgradeneeded = (e) => {
                const thisDb = e.target['result'];
                if (!thisDb.objectStoreNames.contains(this.defaultStore)) {
                    thisDb.createObjectStore(this.defaultStore);
                }
                if (!thisDb.objectStoreNames.contains(this.userInfo)) {
                    thisDb.createObjectStore(this.userInfo);
                }
                if (!thisDb.objectStoreNames.contains(this.unreadchat)) {
                    thisDb.createObjectStore(this.unreadchat);
                }
                if (!thisDb.objectStoreNames.contains(this.unreadNum)) {
                    thisDb.createObjectStore(this.unreadNum);
                }
            };
            openReq.onsuccess = (e) => {
                console.log(" msg -----> indexedDBService.onPageLoad Success");
                this.db = e.target['result'];
                // this.savePerson();
                // this.getByKey(1);
                // this.deleteByKey(1);
            };
            openReq.onerror = (e) => {
                console.log("Error");
                console.dir(e);
            };
        } catch (error) {
            console.log('msg-----> error:' + JSON.stringify(error));
        }

    }
    getByKey(key, storeName = this.defaultStore, callbackFunc: Function) {
        try {
            const transaction = this.db.transaction([storeName], "readonly");
            const store = transaction.objectStore(storeName);
            const obj = store.get(key);// '接收者userid-发送者userId'
            callbackFunc(obj);
        } catch (error) {
            console.log('msg-----> error:' + JSON.stringify(error));
        }

    }
    getAllValues(storeName = this.defaultStore, callbackFunc: Function) {
        try {
            const transaction = this.db.transaction([storeName], "readonly");
            const store = transaction.objectStore(storeName);
            const obj = store.openCursor();
            callbackFunc(obj);
        } catch (error) {
            console.log('msg-----> error:' + JSON.stringify(error));
        }

    }

    getAllValues2(storeName = this.defaultStore, callbackFunc: Function) {
        try {
            const transaction = this.db.transaction([storeName], "readonly");
            const store = transaction.objectStore(storeName);
            store.getAll().onsuccess = (e: any) => {
                const res = e.target.result
                callbackFunc(res);
            }
        } catch (error) {
            console.log('msg-----> error:' + JSON.stringify(error));
        }

    }
    addCallbak(content, key, storeName = this.defaultStore, callbackFunc: Function) {
        try {
            const transaction = this.db.transaction([storeName], "readwrite");
            const store = transaction.objectStore(storeName);
            const req = store.add(content, key);
            req.onerror = (e) => console.log("Error", e.target.error.name + '|' + storeName);
            req.onsuccess = (e) => { callbackFunc(); console.log("save complete callbak 添加成功 " + storeName); };
        } catch (error) {
            console.log('msg-----> error:' + JSON.stringify(error));
        }

    }
    putByKeyCallbak(content, key, storeName = this.defaultStore, callbackFunc: Function) {
        try {
            console.log("put " + storeName);
            const transaction = this.db.transaction([storeName], "readwrite");
            const store = transaction.objectStore(storeName);
            const req = store.put(content, key);
            req.onerror = (e) => console.log("Error", e.target.error.name + '|' + storeName);
            req.onsuccess = (e) => { callbackFunc(); console.log("update complete callbak"); };
        } catch (error) {
            // console.log('msg-----> error:' + JSON.stringify(error));
        }

    }
    deleteByKeyCallbak(key, storeName = this.defaultStore, callbackFunc: Function) {
        try {
            const transaction = this.db.transaction([storeName], "readwrite");
            const store = transaction.objectStore(storeName);
            const req = store.delete(key);
            req.onerror = (e) => console.log("Error", e.target.error.name + '|' + storeName);
            req.onsuccess = (e) => { callbackFunc(); console.log("delete complete"); };
        } catch (error) {
            console.log('msg-----> error:' + JSON.stringify(error));
        }
    }
    add(content, key, storeName = this.defaultStore) {
        try {
            const transaction = this.db.transaction([storeName], "readwrite");
            const store = transaction.objectStore(storeName);
            const req = store.add(content, key);
            req.onerror = (e) => console.log("Error", e.target.error.name + '|' + storeName);
            req.onsuccess = (e) => { console.log("save complete " + storeName + " " + content); };
        } catch (error) {
            console.log('msg-----> error:' + JSON.stringify(error));
        }

    }
    putByKey(content, key, storeName = this.defaultStore) {
        try {
            const transaction = this.db.transaction([storeName], "readwrite");
            const store = transaction.objectStore(storeName);
            const req = store.put(content, key);
            req.onerror = (e) => console.log("Error", e.target.error.name + '|' + storeName);
            req.onsuccess = (e) => { console.log("update complete"); };
        } catch (error) {
            console.log('msg-----> error:' + JSON.stringify(error));
        }

    }
    deleteByKey(key, storeName = this.defaultStore) {
        try {
            const transaction = this.db.transaction([storeName], "readwrite");
            const store = transaction.objectStore(storeName);
            const req = store.delete(key);
            req.onerror = (e) => console.log("Error", e.target.error.name + '|' + storeName);
            req.onsuccess = (e) => console.log("delete complete");
        } catch (error) {
            console.log('msg-----> error:' + JSON.stringify(error));
        }

    }
    clearTableData(storeName, callbackFunc?: Function) {
        try {
            const transaction = this.db.transaction([storeName], "readwrite");
            const objectStore = transaction.objectStore([storeName]);
            const result = objectStore.clear();
            callbackFunc(result);
        } catch (errror) {

        }
    }
    getLastContactCustomerList(callbackFunc: Function) {
        try {
            const that = this;
            const customerList = []; // 未登录返回一个空的客户列表
            const ifLogin = localStorage.getItem('userId') !== 'null';
            if (ifLogin) {
                that.getAllValues('unreadchat', (obj) => {
                    obj.onsuccess = (event) => {
                        const cursor = event.target.result;
                        if (cursor) {
                            if (localStorage.getItem('userId') === String(cursor.key).split("-")[1]) {
                                const contactUserKey = String(cursor.key).split("-")[0];
                                that.getByKey(contactUserKey, 'user', (userData) => {
                                    userData.onsuccess = async (userEvent) => {
                                        if (userData.result) {
                                            const userObj = userData.result;
                                            const tempObj = {
                                                nickname: userObj.nickname === null ? '' : userObj.nickname,
                                                mobile: userObj.work_mobile === null ? '' : userObj.work_mobile,
                                                avator: userObj.avatar_url === null ? 'assets/icon/portrait50@3x.png' : userObj.avatar_url,
                                                link: { type: 'chat' },
                                                id: contactUserKey
                                            };
                                            customerList.push(tempObj);
                                        } else {
                                            await this.http.get("message/userinfo/im/" + contactUserKey, (response) => {
                                                const data = response.data;

                                                const tempObj = {
                                                    nickname: data.nickname === null ? '' : data.nickname,
                                                    mobile: data.work_mobile === null ? '' : data.work_mobile,
                                                    avator: data.avatar_url === null ? 'assets/icon/portrait50@3x.png' : data.avatar_url,
                                                    link: { type: 'chat' },
                                                    id: contactUserKey
                                                };
                                                if (contactUserKey.includes('random')) {
                                                    tempObj.nickname = '访客';
                                                    data.nickname = '访客';
                                                }
                                                customerList.push(tempObj);
                                                this.add(data, contactUserKey, 'user');
                                            }, (error) => {
                                                console.log('msg-----> error:' + JSON.stringify(error));
                                            });
                                        }
                                    };
                                });
                            }
                            cursor.continue();
                        } else {
                            callbackFunc(customerList);
                        }
                    };
                });
            }
        } catch (error) {
            console.log('msg-----> error:' + JSON.stringify(error));
        }
    }
}
